<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="btn">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr  v-for="(obj,index) in arr" :key="index">
          <td>{{index +1}}</td>
          <td>{{obj.name}}</td>
          <td>{{obj.age}}</td>
          <td>{{obj.sex}}</td>
          <td>
            <button @click="btn2(index)">删除</button>
            <button @click="btn3(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
    data () {
      return {
        arr:[
          {
            name:"小明",
            age:18,
            sex:"男"
          },
          {
            name:"张三",
            age:48,
            sex:"男"
          },
          {
            name:"老王",
            age:34,
            sex:"男"
          },
          {
            name:"小丽",
            age:23,
            sex:"女"
          },
        ],
        name:"",
        sex:"",
        age:"",
        isShow:true,
        i:""
      }
    },
    methods: {
      btn(){
        if(this.name == "" || this.age == "" || this.sex == ""){
           alert('请输入内容')
        }else if(this.isShow){
          this.arr.push({
            name:this.name,
            age:this.age,
            sex:this.sex
        })
        }
        else if(this.isShow == false){
          this.arr[this.i].name = this.name
          this.arr[this.i].age = this.age
          this.arr[this.i].sex = this.sex
           this.isShow = true
           this.name = ""
           this.age =""
           this.sex = ""
        }
       
      },
      btn2(theObj){
        let index = this.arr.findIndex(obj => obj.index == theObj.index)
        this.arr.splice(index,1)
      },
      btn3(index){
         this.name = this.arr[index].name,
         this.sex = this.arr[index].sex
         this.age = this.arr[index].age
         this.isShow = false 
         this.i = index
      }
    }
}
</script>